package com.quick.proxy.server;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.watch.WatchMonitor;
import cn.hutool.core.io.watch.Watcher;
import cn.hutool.core.util.ObjectUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.cloud.context.refresh.ContextRefresher;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.File;
import java.nio.file.Path;
import java.nio.file.WatchEvent;

/**
 * Description: 刷新配置类
 * Author: 吃素不吃肉
 * Date: 2023/7/9
 *
 * @author 吃素不吃肉
 */
@Slf4j
@Component
public class Refresh {
    @Qualifier("configDataContextRefresher")
    @Autowired
    private ContextRefresher contextRefresher;


    @PostConstruct
    public void fileCreateMonitor() {
        // 指定监听目录，实际应用需要由外部配置文件进行配置
        String property = System.getProperty("user.dir");
        String dirPath = property + File.separator + "/config";
        File file = FileUtil.file(dirPath);
        if (ObjectUtil.isNull(file) && !file.exists()) {
            log.info("watch monitor {} not exist", dirPath);
            return;
        }
        // 只监听目录的创建事件
        WatchMonitor.create(file, WatchMonitor.ENTRY_MODIFY, WatchMonitor.ENTRY_CREATE)
                .setWatcher(new Watcher() {
                    @Override
                    public void onCreate(WatchEvent<?> watchEvent, Path path) {

                    }

                    @Override
                    public void onModify(WatchEvent<?> watchEvent, Path path) {
                        contextRefresher.refresh();
                        log.info("refresh scope success");
                    }

                    @Override
                    public void onDelete(WatchEvent<?> watchEvent, Path path) {
                    }

                    @Override
                    public void onOverflow(WatchEvent<?> watchEvent, Path path) {
                    }
                })
                .start();
        log.info("watch monitor {} success", file.getAbsolutePath());

    }
}
